'''
Description: 
Version: 2.0
Autor: zyw
Date: 2022-02-24 10:22:53
LastEditors: zyw
LastEditTime: 2022-03-01 15:15:48
'''
import requests
from jsonpath import jsonpath
import datetime, time
import os, sys

base_path = os.path.abspath(os.path.join(os.getcwd(), "."))
sys.path.append(base_path)
from common.hand_conf import conf
from common.hand_path import conf_path
from common.replace_data import replace_data


class BaseTest(object):

    @classmethod
    def prepare_test_data(cls, item):
        """准备测试数据方法"""
        # 第一步：准备数据
        base_url = conf.get('env', 'base_url')
        # 请求头
        headers = eval(conf.get('header', 'login_header'))
        # 1.接口地址
        cls.url = base_url + item['url']
        # 2.接口请求参数
        item["data"] = replace_data(item["data"], cls)
        cls.params = eval(item['data'])
        # 3.请求头
        # 4.获取请求方法，并转换为小写
        cls.method = item['method'].lower()
        # 5.预期结果
        cls.expected = eval(item['expected'])

    @classmethod
    def admin_login(cls):
        """管理员登录方法"""
        # 1.准备登录的接口数据
        url = conf.get('env', 'base_url') + '/auth/login'
        params = {
            'username': conf.get('test_data', 'admin_user'),
            'password': conf.get('test_data', 'password'),
            'picCode': conf.get('test_data', 'picCode')
        }
        headers = eval(conf.get('header', 'login_header'))
        # 2.请求登录
        response = requests.post(url=url, data=params, headers=headers)
        res = response.json()
        # 3.登录成功后提取token
        token = jsonpath(res, '$..token')[0]
        cls.user_id = jsonpath(res, '$..id')[0]
        # 4.将token添加到请求头中
        headers['token'] = token
        cls.headers = headers

    @classmethod
    def manager_login(cls):
        """客户经理登录"""
        # 1.准备登录的接口数据
        url = conf.get('env', 'base_url') + '/auth/login'
        params = {
            'username': conf.get('test_data', 'manager_user'),
            'password': conf.get('test_data', 'password'),
            'picCode': conf.get('test_data', 'picCode')
        }
        headers = eval(conf.get('header', 'login_header'))
        # 2.请求登录
        response = requests.post(url=url, data=params, headers=headers)
        res = response.json()
        # 3.登录成功后提取token
        token = jsonpath(res, '$..token')[0]
        cls.user_id = jsonpath(res, '$..id')[0]
        # 4.将token添加到请求头中
        headers['token'] = token
        cls.headers = headers

    @classmethod
    def add_quoted_price(cls):
        """添加报价基本信息前置"""
        # 第一步：准备数据
        url = conf.get('env', 'base_url') + '/erp/quotedPrice/'
        params = {
            "companyId": "1118",
            "quotedTopic": "接口报价测试 " + datetime.datetime.now().strftime('%Y-%m-%d %H:%S'),
            "customerManagerId": cls.user_id,
            "contactId": "ecdf6243b536477585e4352362ff35b6",
            "priority": 1,
            "productType": 2,
            "note": ""
        }
        # 第二步：请求添加报价基本信息的接口
        response = requests.post(url=url, json=params, headers=cls.headers)
        res = response.json()
        # 提取报价id
        conf.set("test_data", "quoted_price_id", jsonpath(res, '$..id')[0])
        conf.write(open(os.path.join(conf_path, "conf.ini"), "w", encoding='utf-8'))

    @classmethod
    def add_quoted_prince_items_environment(cls):
        """添加报价检测项"""
        url = conf.get('env', 'base_url') + '/erp/quotedPriceItems/'
        params = {
            "quotedPriceId": conf.get('test_data', 'quoted_price_id'),
            "discountType": 1,
            "discount": "",
            "prePayment": "",
            "totalPrice": 3000,
            "favourableAmount": 3000,
            "receiptAmount": 3000,
            "kcbDeducted": 0,
            "groupList": [
                {
                    "dispOrder": 1,
                    "groupName": "环境与可靠性",
                    "rootExperimentTypeIdString": "605813742260850688",
                    "itemList": [
                        {
                            "rootExperimentTypeId": "605813742260850688",
                            "experimentTypeId": "605816392352141312",
                            "experimentTypeName": "低温贮存试验",
                            "itemName": "低温贮存",
                            "deviceSpecs": "0.5m³＜X≤1m³",
                            "standard": "GJB",
                            "feeQuantity": 1,
                            "itemChargeUnit": "天",
                            "itemPrice": 1500,
                            "discount": "",
                            "price": 1500,
                            "quotedPrice": 1500,
                            "offset": 0,
                            "itemPriceType": 1,
                            "itemPriceId": "b185756552f54fbbb3a615fbf2c0149b",
                            "itemAgreementPriceId": "",
                            "note": "",
                            "markId": 0.23567771576943808,
                            "quotedPriceId": "3fef3c174f8b452aa05530251b1983ca"
                        },
                        {
                            "rootExperimentTypeId": "605813742260850688",
                            "experimentTypeId": "605816425101266944",
                            "experimentTypeName": "低温工作试验",
                            "itemName": "低温工作",
                            "deviceSpecs": "0.5m³＜X≤1m³",
                            "standard": "GJB",
                            "feeQuantity": 1,
                            "itemChargeUnit": "天",
                            "itemPrice": 1500,
                            "discount": "",
                            "price": 1500,
                            "quotedPrice": 1500,
                            "offset": 0,
                            "itemPriceType": 1,
                            "itemPriceId": "8b270e92bd3f4ee096c38d7a6f0844a2",
                            "itemAgreementPriceId": "",
                            "note": "",
                            "markId": 1.6186081102712455,
                            "quotedPriceId": "3fef3c174f8b452aa05530251b1983ca"
                        }
                    ]
                }
            ]
        }
        # 第二步: 请求添加报价检测项接口
        response = requests.put(url=url, json=params, headers=cls.headers)
        res = response.json()

    @classmethod
    def add_quoted_prince_items_ele(cls):
        """添加报价检测项"""
        url = conf.get('env', 'base_url') + '/erp/quotedPriceItems/'
        params = {
              "quotedPriceId": conf.get('test_data', 'quoted_price_id'),
              "discountType": 1,
              "discount": "",
              "prePayment": "",
              "totalPrice": 2600,
              "favourableAmount": 2600,
              "receiptAmount": 2600,
              "kcbDeducted": 0,
              "groupList": [
                {
                  "dispOrder": 1,
                  "groupName": "电磁兼容",
                  "rootExperimentTypeIdString": "605813783956426752",
                  "itemList": [
                    {
                      "rootExperimentTypeId": "605813783956426752",
                      "experimentTypeId": "605818459791691776",
                      "experimentTypeName": "辐射骚扰测试",
                      "itemName": "医疗设备10m 暗室辐射骚扰",
                      "deviceSpecs": "",
                      "standard": "GB",
                      "feeQuantity": 1,
                      "itemChargeUnit": "工时",
                      "itemPrice": 1300,
                      "discount": "",
                      "price": 1300,
                      "quotedPrice": 1300,
                      "offset": 0,
                      "itemPriceType": 1,
                      "itemPriceId": "cbdcb25db76343d6b07eb94569826b31",
                      "itemAgreementPriceId": "",
                      "note": "",
                      "markId": 0.6215935968347837,
                      "quotedPriceId": "0168bf4401644add8326c2cb909b1129"
                    },
                    {
                      "rootExperimentTypeId": "605813783956426752",
                      "experimentTypeId": "605818459791691776",
                      "experimentTypeName": "辐射骚扰测试",
                      "itemName": "医疗设备3m 暗室辐射骚扰（1G以上）",
                      "deviceSpecs": "",
                      "standard": "GB",
                      "feeQuantity": 1,
                      "itemChargeUnit": "工时",
                      "itemPrice": 1300,
                      "discount": "",
                      "price": 1300,
                      "quotedPrice": 1300,
                      "offset": 0,
                      "itemPriceType": 1,
                      "itemPriceId": "ed6b5d44135b468db20318c6e1432524",
                      "itemAgreementPriceId": "",
                      "note": "",
                      "markId": 1.7005782211986675,
                      "quotedPriceId": "0168bf4401644add8326c2cb909b1129"
                    }
                  ]
                }
              ]
            }
        # 第二步: 请求添加报价检测项接口
        response = requests.put(url=url, json=params, headers=cls.headers)
        res = response.json()

    @classmethod
    def get_quoted_price_id(cls):
        """查询报价检测项列表id"""
        url = conf.get('env', 'base_url') + '/erp/quotedPrice/getByIdV2/' + conf.get('test_data', 'quoted_price_id')
        response = requests.get(url=url, headers=cls.headers)
        res = response.json()
        print("获取的响应为：{}".format(res))
        conf.set("test_data", "group_list_id", jsonpath(res, '$..groupList[.id]')[0])
        conf.set("test_data", "project_name", jsonpath(res, '$..typeName')[0])
        conf.write(open(os.path.join(conf_path, "conf.ini"), "w", encoding='utf-8'))

    @classmethod
    def assertDictIn(cls, expected, res):
        """字典成员运算的逻辑"""
        for key, value in expected['result'].items():
            if res['result'].get(key) == value:
                pass
            else:
                raise AssertionError('{} not in {}'.format(expected, res))

    @classmethod
    def get_test_time(cls):
        """获取当前时间并加两天，且转换为毫秒时间戳格式"""
        hope_time = (datetime.datetime.now() + datetime.timedelta(days=2)).strftime('%Y-%m-%d %H:%M:%S')
        time_array = time.strptime(hope_time, '%Y-%m-%d %H:%M:%S')
        timestamp = int(time.mktime(time_array)) * 1000
        conf.set('test_data', 'requirement_complete_time', str(timestamp))
        conf.write(open(os.path.join(conf_path, "conf.ini"), "w", encoding='utf-8'))


if __name__ == '__main__':
    # BaseTest.manager_login()
    # BaseTest.add_quoted_price()
    # BaseTest.add_quoted_prince_items()
    BaseTest.get_quoted_price_id()
    # BaseTest.get_test_time()
